import os
import pymysql
from datetime import datetime


def import_firmware_with_pymysql(version, json_path):
    # 数据库配置
    db_config = {
        'host': 'localhost',
        'user': 'root',
        'password': 'Lixy050826.',
        'db': 'My_OTA',
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }

    # 1. 读取原始文件内容（保持原样）
    with open(json_path, 'r', encoding='utf-8') as f:
        original_content = f.read()  # 保留原始换行符和格式

    # 2. 统计块数（按行数计算）
    line_num = sum(1 for line in open(json_path, 'r', encoding='utf-8') if line.strip())

    # 3. 连接数据库
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            # 准备存储路径
            file_path = f"firmware/{version}/firmware_{version}.json"
            os.makedirs(os.path.dirname(file_path), exist_ok=True)

            # 4. 将原始内容原样写入新文件（保持字节级一致）
            with open(file_path, 'w', encoding='utf-8', newline='') as f:
                f.write(original_content)  # 不经过任何JSON解析/重组

            # 5. 插入数据库记录
            sql = """
            INSERT INTO app01_firmware 
            (version, file, release_notes, is_active, created_at)
            VALUES (%s, %s, %s, %s, %s)
            """
            cursor.execute(sql, (
                version,
                file_path,
                f"固件版本 {version},共{line_num}块",
                True,
                datetime.now()
            ))

            connection.commit()
            print(f"成功导入固件版本 {version}，块数: {line_num}")
            return cursor.lastrowid

    except Exception as e:
        print(f"导入失败: {str(e)}")
        connection.rollback()
        return None
    finally:
        connection.close()


# 使用示例
if __name__ == "__main__":
    version = "2.0.0"
    json_path = r"D:\pycharmCODE\OTA_Server\FW_PRE\firmware\e_game\2.0.0\VibrationDetect.json"
    import_firmware_with_pymysql(version, json_path)